package auth

import (
	"errors"
	m "im-server-go/entity/mysql_model"
	"im-server-go/utils"
)

// Login 登录
func Login(telephone, password string) (*m.User, error) {
	user, err := GetUserInfo(telephone)
	if err != nil {
		return nil, err
	}

	if right := utils.CheckPassword(password, user.Password); !right {
		return nil, errors.New("密码错误")
	}

	token, err := utils.GenToken(telephone)
	if err != nil {
		return nil, err
	}

	UpdateToken(user.UserId, token)

	return user, nil
}

// GetUserInfo 获取通过手机号查询用户信息
func GetUserInfo(telephone string) (*m.User, error) {
	uc := m.NewUserCriteria()
	user := uc.AndTelephoneEqualTo(telephone).First()
	if user.UserId == 0 {
		return &user, errors.New("该手机号未注册")
	}
	return &user, nil
}

// UpdateToken 更新 access_token
func UpdateToken(userId int64, token string) {
	uc := m.NewUserCriteria()
	user := uc.AndUserIdEqualTo(userId).First()
	if user.UserId == 0 {
		return
	}
	user.AccessToken = token
	uc.Save(&user)
}
